import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import { CheckSquareOutlined, FileImageOutlined, PaperClipOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ActionType, LightFilter, ProFormCascader, ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-form';
import { Cascader, Col, Flex, Input, Row, Space, Spin, Tag } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import { useEffect, useRef, useState } from 'react';
import { DefaultOptionType } from 'antd/lib/select';
import { useAccess } from 'umi';
import DetailsSubmit from '../../submit/components/DetailsSubmit';
import { findTagColor } from '@/utils/findTagColor';
import moment from 'moment';
import { topicReceiptTree, topicSubmitCondition } from '@/services/api/api-cues-topic';
import ReceiptSubmitTable from './ReceiptSubmitTable';
interface ReceiptSubmitProps {
    id: string;
    receipt: string;
    onRefurbish: () => void;
}

const ReceiptSubmit: React.FC<ReceiptSubmitProps> = ({ id, receipt, onRefurbish }) => {
    const [dataTree, setDataTreeState] = useState<DataNode[]>();
    const [dataCheckTree, setDataCheckTreeState] = useState<any>();
    const access = useAccess();
    const checkTreeKeys = new Array();
    const [drawerFormVisible, setDrawerFormVisibleState] = useState<CuesSubmitData.Analysis>();

    const actionRef = useRef<ActionType>();

    /**
     * 搜索参数
     */
    const [queryParam, setQueryParamState] = useState();


    /**
     * 加载组织树请求网络
     */
    const loadData = async () => {
        try {
            const response = await topicReceiptTree({ id });
            if (response.code === 0) {
                setDataTreeState(readyTreeData(response.data));
                setDataCheckTreeState(checkTreeKeys);
            }
        } catch (error) { }
    };

    /**
     * 预备Tree结构数据
     * @param data
     */
    function readyTreeData(data: Array<UserData.Organization>): any {
        const treeData = new Array();

        if (data) {
            data.forEach((val, idx, array) => {
                treeData.push({
                    title: <div>{val.name}{val.isSubmit === 1 && <Tag color='success' bordered={false} style={{ fontSize: 10 }}>{val.isSubmit === 1 ? '已提交' : ''}</Tag>}{(val.isView === 1 && val.isSubmit === 0) && <Tag color='processing' bordered={false} style={{ fontSize: 10 }}>{val.isView === 1 ? '已阅读' : ''}</Tag>}</div>,
                    key: val.id,
                    icon: val.isView === 1 ? <CheckSquareOutlined /> : <QuestionCircleOutlined />,
                    children: readyTreeData(val.children as Array<UserData.Organization>),
                    type: val.type
                });

                if (val.isView !== undefined && val.isView === 1 && !val.children) {
                    checkTreeKeys.push(val.id);
                }
            });
        }
        return treeData;
    }


    return (
        <DrawerForm
            title="阅读情况"
            trigger={<a>{receipt}</a>}
            drawerProps={{
                size: 'large',
                forceRender: true,
                destroyOnClose: true,
                width: '1350px'
            }}
            submitter={false}
            onOpenChange={(visible) => {
                setDrawerFormVisibleState(visible)

                if (visible) {
                    loadData();
                } else {
                    onRefurbish()
                }
            }}
        >
            <Row gutter={[16, 16]}>
                <Col span={8} style={{
                    maxHeight: '750px', overflow: "auto", overflowX: 'hidden',
                    overflowY: 'scroll',
                    marginTop: 10,
                    scrollbarWidth: 'none',
                }} >
                    <Spin spinning={dataTree && dataTree.length <= 0}>
                        {dataTree && dataTree.length ? (
                            <Row>
                                <Col span={12}>
                                    <Tree treeData={dataTree} checkedKeys={dataCheckTree} checkable style={{ width: '50vw' }} onClick={(select, selectNodes) => {
                                        if (selectNodes?.type === 1) {
                                            setQueryParamState({
                                                articleOrganizationId: selectNodes.key
                                            })
                                        } else if (selectNodes?.type === 2) {
                                            setQueryParamState({
                                                articleCombineId: selectNodes.key
                                            })
                                        }
                                        actionRef.current?.reload()
                                    }} />
                                </Col>
                            </Row>
                        ) : (
                            '暂无数据'
                        )}
                    </Spin>
                </Col>
                <Col span={16}>
                    {drawerFormVisible && <ProTable<CuesSubmitData.SubmitPage>
                        columns={[
                            {
                                title: '报送线索',
                                dataIndex: 'articleName',
                                // copyable: true,
                                search: false,
                                ellipsis: true,
                                width: '300px',
                                align: 'center',
                                key: 'articleName',
                                render: (dom, record, _index, action) => {
                                    return (
                                        <div
                                            style={{
                                                textAlign: 'left',
                                                textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                            }}
                                        >
                                            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
                                            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
                                            <DetailsSubmit
                                                id={record.id}
                                                name={record.articleName}
                                                onRefurbish={() => {
                                                    actionRef.current?.reload();
                                                }}
                                            />
                                        </div>
                                    );
                                },
                            },
                            // {
                            //     title: '选题方向',
                            //     dataIndex: 'articleIndustryName',
                            //     key: 'articleIndustryName',
                            //     width: '80px',
                            //     align: 'center',
                            //     search: false,
                            //     render: (_, row) => {
                            //         let industrys = row?.articleIndustrys;

                            //         if (industrys.length > 2) {
                            //             industrys = industrys.slice(0, 2);
                            //             industrys.push({
                            //                 label: '...',
                            //                 value: '...',
                            //             });
                            //         }

                            //         return (
                            //             <Space size={[0, 8]} wrap >
                            //                 {industrys?.map(
                            //                     (item) =>
                            //                         <Tag key={item.value}>{item.label}</Tag>
                            //                     // <div >{item.label}</div>,
                            //                 )}
                            //             </Space>
                            //         );
                            //     },
                            // },
                            {
                                title: '单位',
                                key: 'articleOrganizationAvatar',
                                dataIndex: 'articleOrganizationAvatar',
                                width: '250px',
                                search: false,
                                align: 'center',
                                valueType: 'avatar',
                                render: (dom, row) => (
                                    <div
                                        style={{
                                            textAlign: 'left',
                                            marginLeft: '16px',
                                        }}
                                    >
                                        <Tag color={findTagColor(row.articleOrganizationTopName)}>
                                            {row.articleOrganizationTopName}
                                        </Tag>
                                        <span>{dom}</span>
                                        {row.articleOrganizationName}
                                    </div>
                                ),
                            },
                            // {
                            //     title: '新闻联络人',
                            //     dataIndex: 'articleAccountName',
                            //     // copyable: true,
                            //     ellipsis: true,
                            //     search: false,
                            //     width: '100px',
                            //     align: 'center',
                            //     key: 'articleAccountName',
                            // },
                            // {
                            //     title: '阅读情况',
                            //     hideInSearch: true,
                            //     hideInTable: access.宣传指令x配置x接收者,
                            //     dataIndex: 'receipt',
                            //     key: 'receipt',
                            //     valueType: 'avatar',
                            //     width: '80px',
                            //     align: 'center',
                            //     search: false,
                            //     render: (dom, record) => {
                            //         // return <ReceiptSubmit id={record.id}  />;
                            //     },
                            // },
                            {
                                title: '创建时间',
                                dataIndex: 'createdTime',
                                key: 'createdTime',
                                width: '120px',
                                align: 'center',
                                search: false,
                            },
                        ]}
                        headerTitle={'报送情况'}
                        actionRef={actionRef}
                        request={async (params = {}) => {

                            const response = await topicSubmitCondition({
                                id: id,
                                ...queryParam,
                                ...params,
                            });

                            return Promise.resolve({
                                data: response.data.data,
                                total: response.data.total,
                                success: response.code === 0,
                            });

                        }}
                        rowKey="id"
                        dateFormatter="string"
                        bordered
                        search={false}
                        ghost
                        pagination={{
                            showQuickJumper: true,
                            showSizeChanger: true,
                            defaultPageSize: 9,
                        }}

                        toolbar={{
                            style: {
                                marginTop: '-16px',
                            },
                        }}
                    />}
                </Col>
            </Row>
        </DrawerForm>
    );
};

export default ReceiptSubmit;
